module PersonHelper

  def uniq_persons
    # Get all persons in a single array
    persons = Array.new
    news_items = @items.select{ |i| 
      begin
        # Using identifier instead of path here, because I got many
        # error when used in preprocess block with i.path. 
        i.identifier =~ /news/
      rescue Nanoc::Errors::Generic
        puts "#{i.identifier} is getting an error"
      end
      }

    news_items.each do |j|
      # Because a news can contines no imagelist...
      if not  j[:imagelist].nil?
        persons << person_nb_from_imagelist(j[:imagelist]) 
      end
    end
    persons.flatten.uniq
  end

# return all persons sorted by image number
  def person_list()
    persons = uniq_persons()
    li = Array.new
    persons.each do |p|
      h = Hash.new
      h[:name] = p
      h[:caps] = person_image_nb(p)
      li << h
    end
    li.sort! {|a, b| b[:caps] <=> a[:caps] }
    li
  end

  def person_image_nb(name)
    nb = 0
    @items.select{ |i| i.path =~ /news/}.each do |j|
      # Because a news can contain no imagelist...
      if not  j[:imagelist].nil?
        j[:imagelist].each do |ili|
          nb=nb+1 if ili[:name] == name
        end
      end
    end
    nb
  end

  # Return image list from the slug of a person
  def person_image_list(slug)
    tmp = YAML::load_file( 'tmp/images_per_person.yml' )
    tmp[slug]
  end

  def person_link(slug)
    if person_image_list(slug).size <= @config[:images_per_page]
      "personnalite/#{slug}/"
    else
      "personnalite/#{slug}-page-1/"
    end
  end

end

